/**
 * 格式化日期时间
 * @param {string|Date} date 日期对象或日期字符串
 * @param {string} format 格式模板，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的日期字符串
 */
export function formatDateTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return '';
  
  // 如果是字符串，转换为Date对象
  if (typeof date === 'string') {
    date = new Date(date);
  }
  
  // 如果是无效日期，返回空字符串
  if (isNaN(date.getTime())) {
    return '';
  }
  
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  
  const padZero = (num) => (num < 10 ? '0' + num : num);
  
  format = format
    .replace(/YYYY/g, year)
    .replace(/MM/g, padZero(month))
    .replace(/DD/g, padZero(day))
    .replace(/HH/g, padZero(hour))
    .replace(/mm/g, padZero(minute))
    .replace(/ss/g, padZero(second));
  
  return format;
}

/**
 * 格式化相对时间（xx分钟前，xx小时前等）
 * @param {string|Date} date 日期对象或日期字符串
 * @returns {string} 相对时间字符串
 */
export function formatRelativeTime(date) {
  if (!date) return '';
  
  // 如果是字符串，转换为Date对象
  if (typeof date === 'string') {
    date = new Date(date);
  }
  
  // 如果是无效日期，返回空字符串
  if (isNaN(date.getTime())) {
    return '';
  }
  
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;
  const week = 7 * day;
  const month = 30 * day;
  const year = 365 * day;
  
  if (diff < minute) {
    const seconds = Math.round(diff / 1000);
    return seconds + '秒前';
  } else if (diff < hour) {
    const minutes = Math.round(diff / minute);
    return minutes + '分钟前';
  } else if (diff < day) {
    const hours = Math.round(diff / hour);
    return hours + '小时前';
  } else if (diff < week) {
    const days = Math.round(diff / day);
    return days + '天前';
  } else if (diff < month) {
    const weeks = Math.round(diff / week);
    return weeks + '周前';
  } else if (diff < year) {
    const months = Math.round(diff / month);
    return months + '个月前';
  } else {
    const years = Math.round(diff / year);
    return years + '年前';
  }
} 